//
//  HWInviteRewardSheet.swift
//  HWanGame
//
//  Created by 王昌健 on 2022/9/15.
//  Copyright © 2022 94Wan. All rights reserved.
//

import UIKit

class HWInviteRewardSheet: MMPopupView {

    private var tapBgView:UIView!
    private var bgView: UIView!
    var titleLabel:UILabel!
    var cancelButton:UIButton!
    var sureButton:UIButton!
    var tipsLabel:UILabel!
    var reduceButton:UIButton!
    var sumButton:UIButton!
    var calculationField:UITextField!
    var sureButtonClick:((_:String)->())?
    @objc var close:(()->())?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        initUI()
        
        initFrame()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

extension HWInviteRewardSheet {
    private func initUI() -> Void {
        type = MMPopupType.sheet
        backgroundColor = UIColor.clear
        attachedView = UIApplication.shared.windows.filter({ $0.isKeyWindow }).last?.rootViewController?.view
        
        tapBgView = UIView.init()
        tapBgView.backgroundColor = UIColor.clear
        addSubview(tapBgView)
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(bacgroundTap(_:)))
        tapBgView.addGestureRecognizer(tap)
        
        bgView = UIView()
        bgView.backgroundColor = .white
        bgView.frame = CGRect(x: 0, y: 0, width: screenWidth, height: 237*widthScale)
        addSubview(bgView)
        bgView.addCorner(conrners: [.topLeft,.topRight], radius: 18*widthScale)
        
        cancelButton = UIButton(type: .custom)
        cancelButton.setTitle("取消", for: .normal)
        cancelButton.addTarget(self, action: #selector(cancelButtonClick(_:)), for: .touchUpInside)
        cancelButton.backgroundColor = .colorWithHexString(hexString: "#EEEEEE")
        cancelButton.setTitleColor(.colorWithHexString(hexString: "#888888"), for: .normal)
        cancelButton.titleLabel?.font = .boldSystemFont(ofSize: 13*widthScale)
        cancelButton.layer.cornerRadius = 14*widthScale
        bgView.addSubview(cancelButton)
        
        sureButton = UIButton(type: .custom)
        sureButton.setTitle("确定", for: .normal)
        sureButton.addTarget(self, action: #selector(sureButtonClick(_:)), for: .touchUpInside)
        sureButton.setTitleColor(.colorWithHexString(hexString: "#FFFFFF"), for: .normal)
        sureButton.titleLabel?.font = .boldSystemFont(ofSize: 13*widthScale)
        sureButton.layer.cornerRadius = 14*widthScale
        sureButton.layer.masksToBounds = true
        sureButton.frame = CGRect(x: 0, y: 0, width: 56*widthScale, height: 28*widthScale)
        bgView.addSubview(sureButton)
        UIColor.gradientColor(view: sureButton, colors: [UIColor.colorWithHexString(hexString: "#FFB60A").cgColor,
                                                         UIColor.colorWithHexString(hexString: "#F66A05").cgColor], start: CGPoint(x: 0, y: 0), end: CGPoint(x: 1, y: 0))
        
        
        titleLabel = HWLabel.createBoldLabel(title: "发放平台币", color: "#333333", font: 16*widthScale)
        bgView.addSubview(titleLabel)
        
        tipsLabel = HWLabel.createLabel(title: "注:发放金额不能大于激励奖金余额", color: "#FF726A", font: 13*widthScale)
        tipsLabel.backgroundColor = .colorWithHexString(hexString: "#FFEDEC")
        tipsLabel.layer.cornerRadius = 14*widthScale
        tipsLabel.textAlignment = .center
        tipsLabel.layer.masksToBounds = true
        bgView.addSubview(tipsLabel)
        
        reduceButton = UIButton(type: .custom)
        reduceButton.setImage(UIImage(named: "inviteRewardReduce"), for: .normal)
        reduceButton.addTarget(self, action: #selector(reduceButtonClick(_:)), for: .touchUpInside)
        bgView.addSubview(reduceButton)
        
        sumButton = UIButton(type: .custom)
        sumButton.setImage(UIImage(named: "inviteRewardSum"), for: .normal)
        sumButton.addTarget(self, action: #selector(sumButtonClick(_:)), for: .touchUpInside)
        bgView.addSubview(sumButton)
        
        calculationField = UITextField()
        calculationField.textAlignment = .center
        calculationField.placeholder = "0.0"
        calculationField.keyboardType = .decimalPad
        calculationField.font = .boldSystemFont(ofSize: 54*widthScale)
        calculationField.textColor = .colorWithHexString(hexString: "#333333")
        calculationField.delegate = self
        calculationField.addTarget(self, action: #selector(calculationFieldChange(_:)), for: .editingChanged)
        bgView.addSubview(calculationField)
        
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrameNotify(_:)), name:UIResponder.keyboardWillChangeFrameNotification, object: nil)
        
    }
    
    private func initFrame() -> Void {
        snp.makeConstraints { make in
            make.width.equalTo(screenWidth)
            make.height.equalTo(screenHeight)
        }
        
        tapBgView.snp.makeConstraints { make in
            make.top.left.right.bottom.equalTo(0)
        }
        
        bgView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
//            make.height.equalTo(237*widthScale)
        }
        
        cancelButton.snp.makeConstraints { make in
            make.top.equalTo(24*widthScale)
            make.left.equalTo(18*widthScale)
            make.width.equalTo(56*widthScale)
            make.height.equalTo(28*widthScale)
        }
        
        sureButton.snp.makeConstraints { make in
            make.top.equalTo(24*widthScale)
            make.right.equalTo(-18*widthScale)
            make.width.equalTo(56*widthScale)
            make.height.equalTo(28*widthScale).priority(.high)
        }
        
        titleLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(27*widthScale)
            make.height.equalTo(23*widthScale)
        }
        
        tipsLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(titleLabel.snp.bottom).offset(12*widthScale)
            make.height.equalTo(28*widthScale)
            make.width.equalTo(212*widthScale)
        }
        
        reduceButton.snp.makeConstraints { make in
            make.left.equalTo(27*widthScale)
            make.top.equalTo(cancelButton.snp.bottom).offset(82*widthScale)
            make.width.height.equalTo(22*widthScale)
            make.bottom.equalTo(-80*widthScale)
        }
        
        sumButton.snp.makeConstraints { make in
            make.right.equalTo(-27*widthScale)
            make.top.equalTo(sureButton.snp.bottom).offset(82*widthScale)
            make.width.height.equalTo(22*widthScale)
        }
        
        calculationField.snp.makeConstraints { make in
            make.height.equalTo(76*widthScale)
            make.left.equalTo(reduceButton.snp.right)
            make.right.equalTo(sureButton.snp.left)
            make.centerY.equalTo(reduceButton)
        }
        
    }
}
extension HWInviteRewardSheet {
    @objc func bacgroundTap(_ tap:UITapGestureRecognizer) -> Void {
        hide()
    }
    
    @objc func cancelButtonClick(_ button:UIButton) -> Void {
        hide()
    }
    
    @objc func sureButtonClick(_ button:UIButton) -> Void {
        if calculationField.text?.count ?? 0 > 0 {
            let num = calculationField.text
            let txt = Float(num ?? "0")
            if txt! > 0 {
                self.sureButtonClick?(calculationField.text!)
            } else {
                showHUD(title: "请输入平台币数量")
            }
            
        } else {
            showHUD(title: "请输入平台币数量")
        }
    }
    
    @objc func reduceButtonClick(_:UIButton) -> Void {
        var num = calculationField.text
        if num?.count ?? 0 > 0 {
            if num == "." ||  num == "0."{
                num = "0.0"
            }
        } else {
            num = "0"
        }
        var txt = Float(num ?? "0")
        txt! -= 0.1
        if txt ?? 0 < 1 {
            txt = 0
        }
        calculationField.text = "\(txt ?? 0)"
    }
    
    @objc func sumButtonClick(_:UIButton) -> Void {
        var num = calculationField.text
        if num?.count ?? 0 > 0 {
            if num == "." ||  num == "0."{
                num = "0.0"
            }
        } else {
            num = "0"
        }
        
        var txt = Float(num ?? "0")
        txt! += 0.1
        calculationField.text = "\(txt ?? 0)"
    }
    
    @objc func calculationFieldChange(_ textField:UITextField) ->Void {
        if textField.text == "." {
            textField.text = "0."
        }
    }
    
    @objc func keyboardWillChangeFrameNotify(_ notify:NSNotification) -> Void {
        let duration = notify.userInfo![UIResponder.keyboardAnimationDurationUserInfoKey] as! Double
        let keyboardFrame = notify.userInfo![UIResponder.keyboardFrameEndUserInfoKey] as! CGRect
        let transformY = keyboardFrame.origin.y - self.frame.size.height;
        UIView.animate(withDuration: duration) {
            
            if transformY == 0.0 {
                self.bgView.transform = CGAffineTransform.init(translationX: 0, y: transformY)
            }else{
                if screenHeight < 812 {
                    self.bgView.transform = CGAffineTransform.init(translationX: 0, y: transformY)
                }else {
                    self.bgView.transform = CGAffineTransform.init(translationX: 0, y: transformY + 34)
                }
            }
            
        }
    }
    
    
}


extension HWInviteRewardSheet: UITextFieldDelegate {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        ///只允许输入一个点
        let existingTextHasDecimalSeparator = textField.text?.range(of: ".")
        let replacementTextHasDecimalSepatator = string.range(of: ".")
        if existingTextHasDecimalSeparator != nil,
           replacementTextHasDecimalSepatator != nil {
            return false
        } else {
            return true
        }
    }
}
